<template>
  <div class="campaign-detail-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1 class="logo">众筹平台</h1>
          <el-menu
            mode="horizontal"
            :default-active="activeMenu"
            class="nav-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/home">首页</el-menu-item>
            <el-menu-item index="/campaigns">众筹列表</el-menu-item>
            <el-menu-item index="/create">创建众筹</el-menu-item>
            <el-menu-item index="/my-campaigns">我的众筹</el-menu-item>
          </el-menu>
          <div class="user-info">
            <span class="username">{{ user.username }}</span>
            <el-button type="text" @click="logout">退出</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <div v-loading="loading" class="detail-container">
          <el-button type="text" icon="el-icon-back" @click="$router.go(-1)" class="back-btn">
            返回
          </el-button>

          <el-card class="detail-card" v-if="campaign.id">
            <div class="campaign-header">
              <div class="header-left">
                <h1>{{ campaign.name }}</h1>
                <el-tag :type="getStatusType(campaign.status)" size="large">
                  {{ campaign.status }}
                </el-tag>
              </div>
            </div>

            <el-divider></el-divider>

            <el-row :gutter="40">
              <el-col :span="16">
                <div class="section">
                  <h3>项目描述</h3>
                  <p class="description">{{ campaign.description }}</p>
                </div>

                <div class="section">
                  <h3>筹款进度</h3>
                  <el-progress
                    :percentage="campaign.progress"
                    :color="getProgressColor(campaign.progress)"
                    :stroke-width="20"
                  />
                  <div class="progress-details">
                    <div class="detail-item">
                      <span class="label">已筹集</span>
                      <span class="value">{{ campaign.pledged }} ETH</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">目标金额</span>
                      <span class="value">{{ campaign.goal }} ETH</span>
                    </div>
                    <div class="detail-item">
                      <span class="label">进度</span>
                      <span class="value">{{ campaign.progress }}%</span>
                    </div>
                  </div>
                </div>

                <div class="section">
                  <h3>项目信息</h3>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="创建者">
                      {{ campaign.creator }}
                    </el-descriptions-item>
                    <el-descriptions-item label="开始时间">
                      {{ formatDate(campaign.startAt) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="结束时间">
                      {{ formatDate(campaign.endAt) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="剩余时间" v-if="campaign.status === 'Active'">
                      {{ getRemainingTime(campaign.endAt) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="我的投资">
                      {{ myPledge }} ETH
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </el-col>

              <el-col :span="8">
                <div class="action-panel">
                  <h3>操作面板</h3>

                  <!-- 投资 -->
                  <div v-if="campaign.status === 'Active' && !isCreator" class="action-section">
                    <el-form :model="pledgeForm" ref="pledgeForm">
                      <el-form-item label="投资金额 (ETH)">
                        <el-input
                          v-model="pledgeForm.amount"
                          type="number"
                          placeholder="请输入投资金额"
                        />
                      </el-form-item>
                      <el-button
                        type="primary"
                        :loading="pledging"
                        @click="handlePledge"
                        style="width: 100%;"
                      >
                        立即投资
                      </el-button>
                    </el-form>
                  </div>

                  <!-- 取消投资 -->
                  <div v-if="campaign.status === 'Active' && myPledge > 0" class="action-section">
                    <el-button
                      type="warning"
                      :loading="unpledging"
                      @click="handleUnpledge"
                      style="width: 100%;"
                    >
                      取消我的投资
                    </el-button>
                  </div>

                  <!-- 提取资金 -->
                  <div v-if="isCreator && campaign.status === 'Successful' && !campaign.claimed" class="action-section">
                    <el-alert
                      title="🎉 恭喜！众筹成功！"
                      type="success"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p style="margin-bottom: 10px; font-weight: bold;">您的众筹项目已成功达标！</p>
                        <div style="background: #f0f9ff; padding: 15px; border-radius: 4px; margin: 10px 0; border-left: 4px solid #67C23A;">
                          <p style="margin-bottom: 8px; font-weight: bold;">💰 可提取金额：</p>
                          <p style="font-size: 24px; font-weight: bold; color: #67C23A; margin: 10px 0;">
                            {{ campaign.pledged }} ETH
                          </p>
                          <ul style="padding-left: 20px; line-height: 1.8; margin-top: 10px;">
                            <li>目标金额：{{ campaign.goal }} ETH</li>
                            <li>完成度：{{ campaign.progress }}%</li>
                            <li>支持者数量：正在统计...</li>
                          </ul>
                        </div>
                        <el-divider></el-divider>
                        <p style="margin: 0; color: #67C23A; font-weight: bold;">
                          <i class="el-icon-wallet"></i> 点击下方按钮，将资金提取到您的 MetaMask 钱包
                        </p>
                      </template>
                    </el-alert>
                    <el-button
                      type="success"
                      size="large"
                      :loading="claiming"
                      @click="handleClaim"
                      style="width: 100%; margin-top: 15px; font-size: 16px; height: 50px;"
                      icon="el-icon-wallet"
                    >
                      {{ claiming ? '提取中...' : '提取资金到钱包' }}
                    </el-button>
                  </div>

                  <!-- 创建者：众筹失败提示 -->
                  <div v-if="isCreator && campaign.status === 'Failed'" class="action-section">
                    <el-alert
                      title="众筹未达标"
                      type="warning"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p style="margin-bottom: 10px; font-weight: bold;">很遗憾，该众筹项目未能达到目标金额。</p>
                        <div style="background: #fff; padding: 15px; border-radius: 4px; margin: 10px 0;">
                          <p style="margin-bottom: 8px; font-weight: bold;">📊 众筹结果：</p>
                          <ul style="padding-left: 20px; line-height: 1.8;">
                            <li>筹集金额：<strong>{{ campaign.pledged }} ETH</strong></li>
                            <li>目标金额：<strong>{{ campaign.goal }} ETH</strong></li>
                            <li>完成度：<strong>{{ campaign.progress }}%</strong></li>
                          </ul>
                        </div>
                        <el-divider></el-divider>
                        <div style="background: #fef0f0; padding: 12px; border-radius: 4px; border-left: 4px solid #E6A23C;">
                          <p style="margin: 0; font-weight: bold; color: #E6A23C;">
                            <i class="el-icon-warning"></i> 退款说明：
                          </p>
                          <p style="margin: 8px 0 0 0; line-height: 1.6;">
                            • 所有支持者可以在众筹详情页点击"申请退款"按钮<br>
                            • 退款将自动返还到支持者的钱包地址<br>
                            • 您无需进行任何操作
                          </p>
                        </div>
                      </template>
                    </el-alert>
                  </div>

                  <!-- 支持者：申请退款（众筹失败）-->
                  <div v-if="!isCreator && campaign.status === 'Failed' && myPledge > 0" class="action-section">
                    <el-alert
                      title="众筹未达标"
                      type="warning"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p style="margin-bottom: 8px;">很遗憾，该众筹项目未能达到目标金额。</p>
                        <p style="margin-bottom: 8px;">
                          您的投资：<strong>{{ myPledge }} ETH</strong>
                        </p>
                        <p style="color: #E6A23C;">
                          <i class="el-icon-info"></i> 您可以申请退款，资金将返还到您的钱包
                        </p>
                      </template>
                    </el-alert>
                    <el-button
                      type="warning"
                      :loading="refunding"
                      @click="handleRefund"
                      style="width: 100%; margin-top: 15px;"
                      icon="el-icon-refresh-left"
                    >
                      申请退款
                    </el-button>
                  </div>

                  <!-- 支持者：众筹已取消提示 -->
                  <div v-if="!isCreator && campaign.status === 'Cancelled' && myPledge > 0" class="action-section">
                    <el-alert
                      title="众筹已取消"
                      type="info"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p style="margin-bottom: 8px;">该众筹项目已被创建者取消。</p>
                        <p style="margin-bottom: 8px;">
                          您的投资：<strong>{{ myPledge }} ETH</strong>
                        </p>
                        <p style="color: #909399;">
                          <i class="el-icon-info"></i> 您可以申请退款，资金将返还到您的钱包
                        </p>
                      </template>
                    </el-alert>
                    <el-button
                      type="info"
                      :loading="refunding"
                      @click="handleRefund"
                      style="width: 100%; margin-top: 15px;"
                      icon="el-icon-refresh-left"
                    >
                      申请退款
                    </el-button>
                  </div>

                  <!-- 取消众筹 -->
                  <div v-if="isCreator && campaign.status === 'Active' && parseFloat(campaign.pledged) === 0" class="action-section">
                    <el-button
                      type="danger"
                      :loading="cancelling"
                      @click="handleCancel"
                      style="width: 100%;"
                    >
                      取消众筹
                    </el-button>
                  </div>

                  <!-- 创建者：众筹已取消提示 -->
                  <div v-if="isCreator && campaign.status === 'Cancelled'" class="action-section">
                    <el-alert
                      title="众筹已取消"
                      type="info"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p>该众筹项目已被取消，未产生任何投资。</p>
                      </template>
                    </el-alert>
                  </div>

                  <!-- 资金已提取 -->
                  <div v-if="isCreator && campaign.claimed" class="action-section">
                    <el-alert
                      title="✅ 资金已提取"
                      type="success"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p style="margin-bottom: 10px; font-weight: bold;">恭喜！您已成功提取众筹资金。</p>
                        <div style="background: #f0f9ff; padding: 15px; border-radius: 4px; margin: 10px 0;">
                          <p style="margin-bottom: 8px; font-weight: bold;">📊 众筹统计：</p>
                          <ul style="padding-left: 20px; line-height: 1.8;">
                            <li>筹集金额：<strong>{{ campaign.pledged }} ETH</strong></li>
                            <li>目标金额：<strong>{{ campaign.goal }} ETH</strong></li>
                            <li>完成度：<strong>{{ campaign.progress }}%</strong></li>
                          </ul>
                        </div>
                        <p style="margin: 10px 0 0 0; color: #67C23A;">
                          <i class="el-icon-circle-check"></i> 资金已安全转入您的 MetaMask 钱包
                        </p>
                      </template>
                    </el-alert>
                  </div>

                  <!-- 支持者：众筹成功提示 -->
                  <div v-if="!isCreator && campaign.status === 'Successful' && myPledge > 0" class="action-section">
                    <el-alert
                      title="🎉 众筹成功！"
                      type="success"
                      :closable="false"
                      show-icon
                    >
                      <template slot="default">
                        <p style="margin-bottom: 8px;">恭喜！您支持的众筹项目已成功达标。</p>
                        <p style="margin-bottom: 8px;">
                          您的投资：<strong>{{ myPledge }} ETH</strong>
                        </p>
                        <p style="color: #67C23A;">
                          <i class="el-icon-success"></i> 感谢您的支持！
                        </p>
                      </template>
                    </el-alert>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import web3Helper from '@/utils/web3';
import contractService from '@/api/contract';

export default {
  name: 'CampaignDetail',
  data() {
    return {
      user: {},
      campaign: {},
      myPledge: 0,
      pledgeForm: {
        amount: ''
      },
      loading: false,
      pledging: false,
      unpledging: false,
      claiming: false,
      refunding: false,
      cancelling: false,
      activeMenu: ''
    };
  },
  computed: {
    campaignId() {
      return parseInt(this.$route.params.id);
    },
    isCreator() {
      const account = web3Helper.getAccount();
      return account && this.campaign.creator &&
        account.toLowerCase() === this.campaign.creator.toLowerCase();
    }
  },
  created() {
    this.loadUserInfo();
    this.loadCampaignDetail();
  },
  methods: {
    loadUserInfo() {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        this.user = JSON.parse(userStr);
      }
    },
    
    async loadCampaignDetail() {
      this.loading = true;
      try {
        if (!web3Helper.getAccount()) {
          await web3Helper.connect();
        }
        
        await contractService.init();
        
        const campaign = await contractService.getCampaign(this.campaignId);
        const status = await contractService.getCampaignStatus(this.campaignId);
        
        const pledged = parseFloat(campaign.pledged);
        const goal = parseFloat(campaign.goal);
        const progress = goal > 0 ? Math.min((pledged / goal) * 100, 100) : 0;
        
        this.campaign = {
          id: this.campaignId,
          ...campaign,
          status,
          progress: Math.round(progress)
        };
        
        // 加载用户投资金额
        const account = web3Helper.getAccount();
        if (account) {
          const pledgeAmount = await contractService.getPledgedAmount(this.campaignId, account);
          this.myPledge = parseFloat(pledgeAmount);
        }
      } catch (error) {
        console.error('加载众筹详情失败:', error);
        this.$message.error(error.message || '加载众筹详情失败');
      } finally {
        this.loading = false;
      }
    },
    
    async handlePledge() {
      if (!this.pledgeForm.amount || parseFloat(this.pledgeForm.amount) <= 0) {
        this.$message.error('请输入有效的投资金额');
        return;
      }
      
      this.pledging = true;
      try {
        await contractService.pledge(this.campaignId, this.pledgeForm.amount);
        this.$message.success('投资成功！');
        this.pledgeForm.amount = '';
        await this.loadCampaignDetail();
      } catch (error) {
        console.error('投资失败:', error);
        this.$message.error(error.message || '投资失败');
      } finally {
        this.pledging = false;
      }
    },
    
    async handleUnpledge() {
      this.$confirm('确定要取消您的投资吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.unpledging = true;
        try {
          await contractService.unpledge(this.campaignId);
          this.$message.success('已成功取消投资！');
          await this.loadCampaignDetail();
        } catch (error) {
          console.error('取消投资失败:', error);
          this.$message.error(error.message || '取消投资失败');
        } finally {
          this.unpledging = false;
        }
      }).catch(() => {});
    },
    
    async handleClaim() {
      this.$confirm('确定要提取资金吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async () => {
        this.claiming = true;
        try {
          await contractService.claim(this.campaignId);
          this.$message.success('资金提取成功！');
          await this.loadCampaignDetail();
        } catch (error) {
          console.error('提取资金失败:', error);
          this.$message.error(error.message || '提取资金失败');
        } finally {
          this.claiming = false;
        }
      }).catch(() => {});
    },
    
    async handleRefund() {
      this.refunding = true;
      try {
        await contractService.refund(this.campaignId);
        this.$message.success('退款成功！');
        await this.loadCampaignDetail();
      } catch (error) {
        console.error('退款失败:', error);
        this.$message.error(error.message || '退款失败');
      } finally {
        this.refunding = false;
      }
    },
    
    async handleCancel() {
      this.$confirm('确定要取消这个众筹活动吗？此操作不可撤销！', '警告', {
        confirmButtonText: '确定取消',
        cancelButtonText: '我再想想',
        type: 'error'
      }).then(async () => {
        this.cancelling = true;
        try {
          await contractService.cancelCampaign(this.campaignId);
          this.$message.success('众筹已取消');
          await this.loadCampaignDetail();
        } catch (error) {
          console.error('取消众筹失败:', error);
          this.$message.error(error.message || '取消众筹失败');
        } finally {
          this.cancelling = false;
        }
      }).catch(() => {});
    },
    
    getStatusType(status) {
      const typeMap = {
        'Active': 'success',
        'Successful': 'success',
        'Failed': 'danger',
        'Cancelled': 'warning',
        'Not Started': 'info'
      };
      return typeMap[status] || 'info';
    },
    
    getProgressColor(percentage) {
      if (percentage < 30) return '#F56C6C';
      if (percentage < 70) return '#E6A23C';
      return '#67C23A';
    },
    
    getRemainingTime(endAt) {
      const now = Math.floor(Date.now() / 1000);
      const remaining = endAt - now;
      
      if (remaining <= 0) return '已结束';
      
      const days = Math.floor(remaining / 86400);
      const hours = Math.floor((remaining % 86400) / 3600);
      const minutes = Math.floor((remaining % 3600) / 60);
      
      if (days > 0) return `${days}天 ${hours}小时`;
      if (hours > 0) return `${hours}小时 ${minutes}分钟`;
      return `${minutes}分钟`;
    },
    
    formatDate(timestamp) {
      const date = new Date(timestamp * 1000);
      return date.toLocaleString('zh-CN');
    },
    
    handleMenuSelect(index) {
      this.$router.push(index);
    },
    
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('user');
        web3Helper.disconnect();
        this.$message.success('已退出登录');
        this.$router.push('/login');
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.campaign-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.logo {
  font-size: 24px;
  color: #409EFF;
  margin: 0;
  margin-right: 40px;
}

.nav-menu {
  flex: 1;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-weight: bold;
  color: #333;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.back-btn {
  margin-bottom: 20px;
  font-size: 16px;
}

.detail-card {
  padding: 20px;
}

.campaign-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h1 {
  margin: 0 0 15px 0;
  color: #333;
}

.section {
  margin-bottom: 40px;
}

.section h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 20px;
}

.description {
  color: #666;
  line-height: 1.8;
  font-size: 16px;
}

.progress-details {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.detail-item .label {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.detail-item .value {
  color: #333;
  font-size: 20px;
  font-weight: bold;
}

.action-panel {
  position: sticky;
  top: 20px;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
}

.action-panel h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.action-section {
  margin-top: 20px;
}

.action-section:first-child {
  margin-top: 0;
}
</style>

